﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using GP.Scripts.Battle;
using UnityEngine;

namespace Gp.Scripts.Core
{
    public class BonusDisposer : IDisposable
    {
        private Action _onDispose;

        public BonusDisposer(Action onDispose)
        {
            _onDispose = onDispose;
        }

        public void Dispose()
        {
            _onDispose?.Invoke();
            _onDispose = null;
        }
    }

    [Serializable]
    public class UnitStatCom : GameEntityStat, IUnitComponent
    {
        private BaseUnit _unit;
        private int _uid = 1;
        
        public UnitStatCom(BaseUnit unit)
        {
            _unit = unit;

            foreach (var field in UnitStat.AllFieldConfigs())
            {
                this[field.Id] = unit.EntityConfig.UnitStat[field.Id];
            }
        }

        /// <summary>
        /// 保留最初的加成信息，包括加成来源
        /// </summary>
        private Dictionary<int, BonusInfo> _bonusInfoMap = new();
        /// <summary>
        /// 总的加成结果，可以直接读取
        /// </summary>
        private Dictionary<int, ModifierValue> _totalModifiers = new();


        /// <summary>
        /// 获取技能增益
        /// </summary>
        /// <param name="field"></param>
        /// <returns></returns>
        public ModifierValue SkillModifiedValue(int field)
        {
            return _totalModifiers.GetValueOrDefault(field, new ModifierValue());
        }
        

        public BonusDisposer AddBonus(BonusInfo bonusInfo)
        {
            _bonusInfoMap[_uid++] = bonusInfo;
            UpdateModifier();
            return new BonusDisposer(() => { _bonusInfoMap.Remove(_uid); UpdateModifier(); });
        }
        
        
        public IEnumerator OnTurnEnd()
        {
            yield break;
        }

        public IEnumerator OnTurnStart()
        {
            yield break;
        }

        
        private void UpdateModifier()
        {
            _totalModifiers.Clear();
            foreach (var bonus in _bonusInfoMap.Values.SelectMany(x => x.Bonus))
            {
                _totalModifiers[bonus.BonusField] += bonus.ModifierValue;
            }
        }
    }
}